package com.xzgj.api.config;

import com.alibaba.cola.dto.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;
import java.util.List;

/**
 * @author hxh
 * @version 1.0.0
 * @date 2024/3/8
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    public static final String ERROR_CODE = "500";
    @ExceptionHandler(BindException.class)
    public Response handlerBindException(BindException e) {
        return Response.buildFailure(ERROR_CODE, e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        ObjectError objectError = allErrors.get(0);
        return Response.buildFailure(ERROR_CODE, objectError.getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        return Response.buildFailure(ERROR_CODE, e.getMessage());
    }
}
